<template>
  <div class="staff-account">
    <div class="account-select">
      <el-form>
        <el-form-item style="margin-bottom: 20px;">
          <div class="select-dept">
            <el-cascader :options="data"
              :show-all-levels="false"
              :props="{ value: 'id', label: 'department', children: 'adminDepartments' }"
              v-model="defaultValue"
              change-on-select
              @change="handleCascader">
            </el-cascader>
          </div>
          <el-dropdown trigger="hover"
            @command="dropdownStateChange">
            <span class="el-dropdown-link">
              {{dropdownValue}}
              <i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown"
              class="state-staff-select">
              <el-dropdown-item :command="{value: -2, title: '全部状态'}">
                全部状态
              </el-dropdown-item>
              <el-dropdown-item :command="{value: 1, title: '启用'}">
                启用
              </el-dropdown-item>
              <el-dropdown-item :command="{value: 0, title: '禁用'}">
                禁用
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <div class="input-with-select el-input el-input-group el-input-group--append">
            <input autocomplete="off"
              placeholder="请输入员工账号/姓名/职位/手机"
              type="text"
              validateevent="true"
              class="el-input__inner"
              v-model="searchKey"
              @keyup.enter="handelSearch">
          </div>
          <el-button type="primary"
            size="small"
            style="margin-left:15px"
            @click="handelSearch">
            <i class="el-icon-search"></i>
          </el-button>
          <el-button type="primary"
            size="small"
            style="float: right;"
            @click="addAccount"
            v-has="'addstaff'">新增账号</el-button>
        </el-form-item>
        <el-form-item style="margin-bottom:20px;"
          v-has="'userimport'">
          <el-upload class="fl"
            :http-request="sendChange"
            action="https://jsonplaceholder.typicode.com/posts/"
            style="margin-right:20px"
            :show-file-list="false">
            <el-button size="small"
              type="primary">导入</el-button>
          </el-upload>
          <el-button type="primary"
            size="small"
            @click="_exportToLog"
            :disabled="!tableData.length"
            v-has="'outputstafflist'">导出</el-button>
        </el-form-item>
        <el-form-item>
        </el-form-item>
        <el-form-item>
          <el-table :data="tableData"
            style="width: 100%"
            max-height="550">
            <el-table-column prop="account"
              label="头像">
              <template slot-scope="scope">
                <div class="avarta-wrap">
                  <img :src="scope.row.photo"
                    v-if="scope.row.photo"
                    width="40"
                    height="40" />
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="account"
              label="账号">
            </el-table-column>
            <el-table-column prop="name"
              label="姓名">
            </el-table-column>
            <el-table-column prop="account"
              label="性别">
              <template slot-scope="scope">
                <div class="avarta-wrap">
                  {{scope.row.sex ==1? "男":"女"}}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="position"
              label="职位">
            </el-table-column>
            <el-table-column prop="dept"
              label="部门">
            </el-table-column>
            <el-table-column prop="mobile"
              label="手机">
            </el-table-column>
            <el-table-column prop="email"
              label="邮箱">
            </el-table-column>
            <el-table-column prop="state"
              label="状态">
            </el-table-column>
            <el-table-column label="操作"
              width="300">
              <template slot-scope="scope">
                <el-button @click.native.prevent="stateRow(scope.$index, tableData)"
                  type="text"
                  v-has="'updatestaffstatus'"
                  v-if="isShow(tableData[scope.$index].isAdmin)"
                  size="small">
                  {{tableData[scope.$index].button}}
                </el-button>
                <el-button @click.native.prevent="editRow(scope.$index, tableData)"
                  type="text"
                  size="small"
                  v-has="'updatestaff'">
                  修改
                </el-button>
                <el-button @click.native.prevent="resetPassword(scope.row.id)"
                  type="text"
                  size="small"
                  v-if="isShow(tableData[scope.$index].isAdmin)">
                  重置密码
                </el-button>
                <el-button @click.native.prevent="_delete(scope.row)"
                  type="text"
                  size="small"
                  v-if="isShow(tableData[scope.$index].isAdmin)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item style="margin-top: 20px;">
          <el-pagination @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageSize"
            layout="total, prev , pager , next, sizes, jumper"
            :total="allPage">
          </el-pagination>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import {
  getStaffList,
  getDeptstaff,
  setStaffState,
  resetAccountPassword,
  getExportStafflist,
  importExcel
} from "../../../public/js/setting";

import { exportToExcel, importToJson } from "@/public/js/util";
export default {
  name: "Staff",
  data() {
    return {
      searchKey: "",
      data: [{}],
      dropdownValue: "全部状态",
      defaultValue: [-1],
      state: [],
      tableData: [],
      copyData: [],
      pageNum: 1,
      pageSize: 10,
      allPage: 0,
      stateValue: -2,
      stateData: null,
      dept: -1,
      suppliersUserId: null,
      exportLogList: [],
      importFile: "",
      _isAdmin: false
    };
  },
  created() {
    this.getStaffLists();
    this._isAdmin = sessionStorage.getItem("isAdmin");
  },
  mounted() {
    getDeptstaff().then(res => {
      if (res.data.errCode === 0) {
        const deptArray = Array.from(res.data.adminDepartments);
        this.data = res.data.adminDepartments;
        this.data.unshift({
          adminDepartments: null,
          id: -1,
          department: "全部部门"
        });
      }
    });
  },
  methods: {
    isShow(isAdmin) {
      //管理员
      if (this._isAdmin == 0) {
        return isAdmin ? true : false;
      } else {
        if (!this._isAdmin) {
          return false;
        }
      }
    },
    //获取导出房务日志数据
    _getExportLogList(callback) {
      getExportStafflist({
        searchKey: this.searchKey,
        dept: this.dept,
        state: this.stateValue
      }).then(res => {
        this.exportLogList = res.data.suppliersUserEntities;
        //回调函数
        callback();
      });
    },
    //导出日志
    _exportToLog() {
      this._getExportLogList(() => {
        const tHeader = [
          "用户名",
          "姓名",
          "性别",
          "职位",
          "部门",
          "手机",
          "邮箱",
          "状态"
        ];
        const filterVal = [
          "account",
          "name",
          "sexCN",
          "position",
          "dept",
          "mobile",
          "email",
          "state"
        ];
        exportToExcel(tHeader, filterVal, this.exportLogList, "员工表");
      });
    },
    // 导入
    sendChange(uploadFile) {
      if (
        uploadFile.file.type !==
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      ) {
        this.$message.error("请选择Excel格式的文件");
        return false;
      } else {
        var reader = new FileReader(uploadFile.file); //新建一个FileReader
        reader.readAsBinaryString(uploadFile.file, "UTF-8");
        reader.onload = evt => {
          let originData = evt.target.result;
          let data = importToJson(originData);
          console.log(JSON.stringify(data));
          importExcel({
            json: JSON.stringify(data)
          }).then(res => {
            console.log(res);
            if (!res.data.errCode) {
              this.$message({
                type: "success",
                message: "导入成功"
              });
            }
            this.getStaffLists();
          });
        };
      }
    },
    handleCascader(val) {
      this.dept = parseInt(val[val.length - 1]);
      this.pageNum = 1;
      this.getStaffLists();
    },
    handelSearch() {
      this.pageNum = 1;
      this.getStaffLists();
    },
    editRow(index) {
      sessionStorage.setItem("accountID", this.tableData[index].id);
      this.$router.push("/index/edit_account");
    },
    dropdownStateChange(data) {
      this.stateValue = data.value;
      this.getStaffLists();
      this.pageNum = 1;
      this.dropdownValue = data.title;
    },
    _delete(data) {
      this.$confirm("此操作将永久删除该员工, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.suppliersUserId = data.id;
          this.stateData = -1;
          setStaffState(this).then(res => {
            if (res.data.errCode === 0) {
              this.tableData = res.data.suppliersUserEntities;
              this.allPage = res.data.total;
              this.$message.success("修改成功");
            }
          });
        })
        .catch(() => {});
    },
    stateRow(index, rows) {
      this.suppliersUserId = this.tableData[index].id;
      this.tableData[index].state === "正常"
        ? (this.stateData = 0)
        : (this.stateData = 1);
      this.tableData[index].state === "正常"
        ? (this.text = "禁用")
        : (this.text = "启用");
      this.$confirm("此操作将" + this.text + "该员工, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          setStaffState(this).then(res => {
            if (res.data.errCode === 0) {
              this.tableData = res.data.suppliersUserEntities;
              this.allPage = res.data.total;
              this.$message.success("修改成功");
            }
          });
        })
        .catch(() => {});
    },
    getStaffLists() {
      getStaffList(this).then(res => {
        if (res.data.errCode === 0) {
          this.tableData = res.data.suppliersUserEntities;
          this.allPage = res.data.total;
        }
      });
    },
    handleSizeChange(val) {
      this.pageSize = this.allPage = val;
      this.getStaffLists();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getStaffLists();
    },
    addAccount() {
      this.$router.push("/index/add_account");
    },
    // 重置密码
    resetPassword(id) {
      this.$confirm("此操作将重置该员工密码, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          resetAccountPassword(id).then(res => {
            if (res.data.errCode === 0) {
              this.$message.success("重置密码成功");
            }
          });
        })
        .catch(() => {});
    }
  }
};
</script>
<style lang="scss" scoped>
.button-style {
  float: left;
  width: 30%;
}
.select-dept span {
  font-size: 12px;
  line-height: 34px;
}
.el-dropdown {
  line-height: 35px;
}
.el-dropdown,
.input-with-select,
.select-dept {
  float: left;
}
.staff-account {
  .account-select {
    .el-form {
      .el-form-item {
        .el-form-item__content {
          .el-dropdown {
            margin-right: 30px;
          }
          /*搜索input样式*/
          .el-input {
            width: 400px;
            input {
              height: 34px;
              line-height: 34px;
            }
            .el-input-group__append {
              padding: 0 14px;
              .el-button {
                margin: -14px;
              }
              button {
                padding: 8px 9px;
              }
            }
          }
        }
      }
    }
  }
}
.avarta-wrap {
  display: flex;
  align-items: center;
}
</style>
